package com.sunfeng.netty.atguigu2.nio;

import java.io.IOException;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer1 {
    public static void main(String[] args) throws IOException {
        // 创建一个ServerSocketChannel

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        Selector selector = Selector.open();

        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8888));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {


            if (selector.select(1000) == 0) {
                System.out.println("服务器等待了一秒,无连接！");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            if (keyIterator.hasNext()) {
                SelectionKey selectionKey = keyIterator.next();

                if(selectionKey.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();

                    System.out.println("客户端连接成功生成一个socketChannel"+socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ,ByteBuffer.allocate(1024));
                }
                if(selectionKey.isReadable()){
                    SocketChannel socketChannel =(SocketChannel) selectionKey.channel();

                    ByteBuffer byteBuffer =(ByteBuffer)selectionKey.attachment();

                    socketChannel.read(byteBuffer);

                    System.out.println(new String(byteBuffer.array()));

                }
                keyIterator.remove();
            }


        }


    }
}
